"use strict";

$(function () {
    $(".modal .close").click(function () {
        $(".modal").addClass("hide");
    });

    //获得所有的港区和航道
    $.ajax({
        type: "post",
        url: "/wzmanage/port/queryAll",
        contentType: "application/json;charset=utf-8",
        success: function success(data) {
            $.ajax({
                type: "post",
                url: "/wzmanage/channel/queryAll",
                contentType: "application/x-www-form-urlencoded;charset=utf-8",
                success: function success(da) {
                    console.log(da)
                    changeP2C(data,da)//航道和港口的阈值修改
                    // newP2C(data,da)//新建航道与港口的切换

                }
            })
        }
    })
    //港区和航道的切换
    function changeP2C(port,channel){
        $("ul.weekinfo").unbind()
        loadPord(port);
        selectPort("/wzmanage/threshold/queryAll?stationName=")
        $("ul.weekinfo").on("click", "li", function () {
            if($(this).hasClass("active"))return
            var index = $(this).index();
            $(".user-list tfoot button").prop("disabled", false);
            $(this).addClass("active").siblings().removeClass("active");
            if (index == 0) {
                loadPord(port)
                // selectPort("/wzmanage/revise/listThree")
                // updateRevise("/wzmanage/revise/updateThree");
                selectPort("/wzmanage/threshold/queryAll?stationName=")
            } else {
                loadPord(channel)
                selectPort("/wzmanage/threshold/queryAll?stationName=")
                // selectPort("/wzmanage/revise/listWeek")
                // updateRevise("/wzmanage/revise/updateWeek");
            }
        });
    }

    //加载列表
    function loadList(url) {
        $.ajax({
            type: "get",
            url:url ,
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            success: function success(data) {
                if (data instanceof Array && data.length > 0) {
                    for (var i = 0, html; i < data.length; i++) {
                        html += "<tr>\n                            \n                                    <td class=\"name selInfo\">\n                                       <span>" + (i + 1) + "</span>\n                                        <input class=\"id\"  type=\"hidden\" value=\"" + data[i].id + "\">\n                                    </td>\n                                \n                                    <td class=\"stationName\">" + data[i].stationName + "</td> \n           \n                                    <td class=\"station\">" + data[i].station + "</td> \n                           \n                                    <td class=\"names\">" + data[i].name + "</td> \n                                    <td class=\"threshold\">"+"<div>" + data[i].threshold + "</div></td> \n                                    <td class=\"updaterole\">\n                                        <button class=\"btn btn-primary btn-large updateRes\" >\u4FEE\u6539</button><a href=\""+data[i].locked+"\" class=\"btn btn-primary btn-small\">"+(data[i].locked?"开启短信提醒":"关闭短信提醒")+"</a>\n                                        \n                                     \n                                    </td>         \n                                </tr>";
                    }
                    $(".user-list tbody").html(html);
                }else {
                    $(".user-list tbody").html('<tr><td colspan="6">暂无内容</td></tr>');
                }
            },
            error: function error(er) {
                console.log(er);
            }
        });
    };
    //显示增加航道的页面
    $(".add-del-person a").click(function(e){
        e.preventDefault();
        var station=$("#selRain p").find("span").attr("data-toggle")
        var str=$("#selRain p").find("span").html()
        console.log( $(".user-form input[name=station]"))
        $(".user-form input[name=stationName]").val(str)
        $(".user-form input[name=station]").val(station)
        $(".user-form input[type=text]").val('')
        typeOptions()
        $(".new-add").removeClass("hide");
        addThreshold(str)
    })
    //更新阈值
    $(".user-list").on("click", "button", function () {
        var that=$(this)
        var ht = $(this).html();
        var threshold = $(this).parent().siblings('.threshold').find("div");
        if (ht == "修改"||ht == "已修改") {
            threshold.attr("contenteditable", "true").focus();
            $(this).html("保存");
        } else if (ht == "保存") {
            var id = $(this).parent().siblings().find(".id").val();
            var names = $(this).parent().siblings('.names');
            var stationName = $(this).parent().siblings('.stationName').html();
            var station = $(this).parent().siblings('.station').html();
            var locked=$(this).siblings("a").attr("href")
            var obj = { id: id, threshold: threshold.html(), name: names.html(),station:station,stationName:stationName };
            console.log(obj);
            $.ajax({
                type: "post",
                url: "/wzmanage/threshold/update",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(obj),
                success: function success(data) {
                    console.log(data);
                    if (data == "OK") {
                        // ht.html("")
                        // loadList();
                        threshold.attr("contenteditable", "false")
                        that.html("修改");
                        $(".add-success h3").html("修改成功");
                        $(".add-success").css("display", "block");
                        setTimeout(function () {
                            $(".add-success").fadeOut();
                        }, 500);
                    }
                    console.log(data);
                }
            });
        }
    });
    //选择航道或港区，显示不同的预报
    function selectPort(url) {
        var h = $('.selectList ul li').eq(0).attr("i")
        loadList(url+h);
        $(".selectList").unbind()
        $(".selectList").mouseenter(function () {
            $(this).find(".rain-cn").removeClass("hide")
        })
        $(".selectList").on("click", "li", function () {
            var t = $(this).attr("i")
            loadList(url+t);
            $(".selectList p").html('<span data-toggle="'+$(this).attr("data-toggle")+'">'+$(this).html()+'</span><b></b>')
            $(this).parent().parent().addClass("hide")


        })
    }
    //生成不同的港区
    function loadPord(data){
        for(var i=0,html='';i<data.length;i++){
            html+='<li data-toggle="'+data[i].stationId+'" i="'+data[i].name+'">'+data[i].name+'</li>'
        }
        $(".rain-cn ul").html(html)
        $("#selRain p").html('<span data-toggle="'+data[0].stationId+'">'+data[0].name+'</span><b></b>')
    }
    //添加阈值
    function addThreshold(station){
        $(".new-add .save").unbind()
        $(".new-add .save").click(function () {
            var obj = $(".user-form").serializeObject();
            if (isEmpty() == 1) {
                return;
            }
            console.log(JSON.stringify(obj))
            $.ajax({
                url: "/wzmanage/threshold/add",
                type: "post",
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(obj),
                success: function success(data) {
                    console.log("update" + data);
                    if (data == "OK") {
                        $('body').css({
                            "overflow-x": "auto",
                            "overflow-y": "auto",
                            'padding-right': '0px'
                        });
                        $(".new-add").addClass("hide");
                        $(".add-success h3").html("添加成功");
                        $(".add-success").css("display", "block");
                        setTimeout(function () {
                            $(".add-success").fadeOut();
                        }, 500);
                        console.log(station)
                      loadList("/wzmanage/threshold/queryAll?stationName="+station);
                    }
                },
                error: function error(data) {
                    console.log(data);
                }
            });
        });
    }
    function isEmpty() {
        var inps = $(".new-add").find("input");

        for (var i = 0; i < inps.length; i++) {
            if (!inps[i].value) {
                inps[i].focus();
                $(inps[i]).attr("placeholder", "不能为空");
                return 1;
            }
        }

    }
    //切换航道与港口
    function newP2C(port,channel){
        $("#portChannel").unbind()
        newSelect(port,"港口:")
        $("#portChannel").on("change",function(){
            var val=$(this).val()
            if(val=="港口"){
                newSelect(port,"港口:")
            }else {
                newSelect(channel,"航道:")

            }
            console.log(val)
        })
    }

    function newSelect(data,text){
        for(var i=0,html='';i<data.length;i++){
            html+='<option value="'+data[i].name+'">'+data[i].name+'</option>'
        }
        $("#subPortChannel").html(html)
        $(".subPortChannel").html(text)
    }
    function typeOptions(){
        $.ajax({
            type:'get',
            url:"/wzmanage/threshold/queryTypes",
            dataType:"json",
            success:function (data) {
                console.log(data)
                if(data instanceof Array){
                    for(var i=0,html='';i<data.length;i++){
                        html+='<option value="'+data[i].name+'">'+data[i].name+'</option>'
                    }
                    $("#threshold-type").html(html)
                }
            }
        })
    }
    //短信功能的开启和关闭
    $(".user-list tbody").on("click","a",function(e){
        e.preventDefault();
        var that=$(this)
        var id = $(this).parent().siblings().find(".id").val();
        var locked=$(this).attr("href")=="false"?true:false
        console.log(locked,id)
        $.ajax({
            type: "post",
            url: "/wzmanage/threshold/update",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify({id:id,locked:locked}),
            success: function (data) {
                console.log(data)
                if(data=="OK"){
                    // that.html("开启短信提醒");
                    var str=$("#selRain p span").html()
                    loadList("/wzmanage/threshold/queryAll?stationName="+str);
                    $(".add-success h3").html("修改成功");
                    $(".add-success").css("display", "block");
                    setTimeout(function () {
                        $(".add-success").fadeOut();
                    }, 500);
                }
            }
        })
    })
    //插件
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name]) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
});